<script setup lang="ts">
import { useUserStore } from "@/store/modules/user";
import { reactive, ref } from "vue";
import { sexOption } from "@/common/option";
import { updateUserInfo } from "@/api/user/user";
const userStore = useUserStore();


const formData = reactive({
  avatar: userStore.getUser?.headImgUrl,
  gender: userStore.getUser?.gender,
  introduce: userStore.getUser?.introduction,
  nickname: userStore.getUser?.nickName,
  sound: userStore.getUser?.sound,
});
console.log(formData);

const form = ref<HTMLFormElement>();
const rules = {
  // 对name字段进行必填验证
  nickname: {
    rules: [
      {
        required: true,
        errorMessage: "请输入昵称",
      },
      {
        minLength: 1,
        maxLength: 20,
        errorMessage: "昵称长度在 {minLength} 到 {maxLength} 个字符",
      },
    ],
  },
  // 对email字段进行必填验证
  email: {
    rules: [
      {
        format: "email",
        errorMessage: "请输入正确的邮箱地址",
      },
    ],
  },
};

const submit = (form: any) => {
  form
    .validate()
    .then(() => {
      updateUserInfo(formData).then((res) => {
        uni.showToast({
          title: "修改成功",
          icon: "none",
          duration: 1000,
        });
        userStore.getuserInfo();
        uni.navigateBack({
          delta: 1,
        });
      });
    })
    .catch((err) => {
      console.log("表单错误信息：", err);
    });
};
</script>

<template>
  <view class="x-userinfo">
    <uni-forms ref="form" :modelValue="formData" :rules="rules">
      <uni-forms-item label="头像" name="avatar">
        <uploadFile v-model="formData.avatar" />
      </uni-forms-item>
      <uni-forms-item label="昵称" name="nickname">
        <uni-easyinput type="text" v-model="formData.nickname" placeholder="请输入姓名" />
      </uni-forms-item>
      <uni-forms-item label="性别" name="gender">
        <uni-data-checkbox v-model="formData.gender" :localdata="sexOption" />
      </uni-forms-item>
      <uni-forms-item label="简介" name="introduce">
        <uni-easyinput
          type="textarea"
          v-model="formData.introduce"
          placeholder="请输入自我介绍"
        />
      </uni-forms-item>
    </uni-forms>

    <button class="x-button" type="primary" @click="submit(form)">确定修改</button>
  </view>
</template>

<style lang="scss" scoped>
.x-userinfo {
  padding: 4vw;
}
</style>
